import 'package:flutter/material.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/empty_widget.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/components/refresh_footer.dart';
import 'package:kxy_flutter_app/components/refresh_header.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/news.dart';
import 'package:kxy_flutter_app/view/news/news_item_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CollectNewsView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return CollectNewsViewState();
  }
}

class CollectNewsViewState extends State<CollectNewsView> {
  List<News> newsList = new List<News>();
  int page = 1;
  int totalCount = 0;
  Future loadFuture;
  RefreshController refreshController = new RefreshController();

  @override
  void initState() {
    loadFuture = reload();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('新闻收藏')),
      body: FutureBuilder(
        future: loadFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return newsListWidget();
          }
          return LoadingWidget();
        },
      ),
    );
  }

  Widget newsListWidget() {
    if (newsList.length == 0) {
      return EmptyWidget(onRefresh: reload);
    }

    return SmartRefresher(
      controller: refreshController,
      enablePullDown: true,
      enablePullUp: true,
      header: RefreshHeader(),
      footer: RefreshFooter(),
      onLoading: () async {
        if (totalCount > newsList.length) {
          await loadMore();
          refreshController.loadComplete();
        } else {
          refreshController.loadNoData();
        }
      },
      onRefresh: () async {
        await reload();
        refreshController.refreshCompleted();
      },
      child: ListView.builder(
        itemBuilder: (cxt, index) {
          return NewsItemWidget(
            news: newsList[index],
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
          );
        },
        itemCount: newsList.length,
      ),
    );
  }

  Future reload() async {
    page = 1;
    newsList.clear();
    await loadMore();
  }

  Future loadMore() async {
    var res = await Http.instance.post(
      '/news-app/coll/collNewsList',
      params: {
        'page': page,
        'limit': 20,
        'userId': Auth.instance.userId,
      },
    );

    if (res.code == 200) {
      setState(() {
        page++;
        totalCount = res.data['totalCount'];
        (res.data['list'] as List).forEach((item) {
          var news = News.fromJson(item);
          newsList.add(news);
        });
      });
    }
  }
}
